package com.wfm.lock.readwriteandstamped;

import java.util.concurrent.locks.StampedLock;

class StampedLockExample {
    private final StampedLock stampedLock = new StampedLock();
    private int data = 0;

    public int read() {
        long stamp = stampedLock.tryOptimisticRead();
        int currentData = data;
        if (!stampedLock.validate(stamp)) {
            stamp = stampedLock.readLock();
            try {
                currentData = data;
            } finally {
                stampedLock.unlockRead(stamp);
            }
        }
        return currentData;
    }

    public void write() {
        long stamp = stampedLock.writeLock();
        try {
            data++;
        } finally {
            stampedLock.unlockWrite(stamp);
        }
    }
}
